const baseUrl = 'https://testzh.dpcpower.com';//测试服务
// const baseUrl = 'https://zh.dpcpower.com'; //正式服务
// const baseUrl = 'http://192.168.20.108:8002'

function service(options = {}, method, data = {}) {
	let token = uni.getStorageSync('token') || '';
	options.url = `${baseUrl}${options.url}`;
	//配置请求头
	options.header = {
		'content-type': 'application/json',
		// 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
		'Authorization': token
	};
	if (options.url.includes('/login')) {
		options.header['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
	}

	options.method = method;

	options.data = data;
	return new Promise((resolved, rejected) => {
		//成功
		options.success = (res) => {
			let code = res.data.code;
			if (+code === 200) { //请求成功
				resolved(res.data);
			} else if (code == 401) {
				uni.reLaunch({
					url: '/pages/login/index'
				})
			} else {
				if (!Array.isArray(res.data)) {
					uni.showToast({
						icon: 'none',
						duration: 4000,
						title: `${res.data.message}`
					})
				}
				rejected(res.data); //错误
			}
		}
		//错误
		options.fail = (err) => {
			if (err.errMsg == 'request:fail timeout') {
				uni.showToast({
					title: '请求超时，请稍后重试!',
					duration: 4000,
					icon: "none"
				});
			} else if (err.errMsg == 'request:fail ') {
				uni.showToast({
					title: '网络异常，请检查网络!',
					duration: 4000,
					icon: "none"
				});
			}
			rejected(err); //错误
		}
		uni.request(options);

	})
}
export default service;
